package cn.honglian.org.service.impl;

import cn.honglian.aop.Log_Aop;
import cn.honglian.basic.domain.BaseQuery;
import cn.honglian.basic.service.impl.BaseServiceImpl;
import cn.honglian.basic.util.PageList;
import cn.honglian.org.domain.Department;
import cn.honglian.org.mapper.DepartmentMapper;
import cn.honglian.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    @Log_Aop(name = "这是根据id查询一条")
    public Department findById(Long id) {
        return departmentMapper.findById(id);
    }

    @Override
    @Log_Aop(name = "这是查询所有条数")
    public List<Department> findAll() {
        return departmentMapper.findAll();
    }

    @Override
    @Log_Aop(name = "这是添加一条数据")
    public void add(Department t) {
        departmentMapper.add(t);
    }

    @Override
    @Log_Aop(name = "这是根据id修改一条数据")
    public void update(Department t) {
        departmentMapper.update(t);
    }

    @Override
    @Log_Aop(name = "这是根据id删除一条")
    public void delete(Long id) {
        departmentMapper.delete(id);
    }

    @Override
    @Log_Aop(name = "这是查询列表")
    public PageList<Department> queryByPage(BaseQuery BaseQuery) {
        Integer totals = departmentMapper.queryByCount(BaseQuery);
        if (null == totals || 0 == totals) {
            return new PageList<Department>(0, new ArrayList<>());
        }
        List<Department> rows = departmentMapper.queryByPage(BaseQuery);
        return new PageList<Department>(totals, rows);
    }

    @Override
    @Log_Aop(name = "这是批量删除")
    public void batchDelete(List<Long> ids) {
        departmentMapper.batchDelete(ids);
    }

    @Override
    @Log_Aop(name = "查询所有的部门无限极树")
    public List<Department> getTree() {
        ArrayList<Department> treeAll = new ArrayList<>();
        List<Department> allTree = findAll();
        for (Department dept :allTree) {
            if(null==dept.getParentId()){
                treeAll.add(dept);
            }else {
                for (Department deptObj :allTree){
                    if (deptObj.getId()==dept.getParentId()){
                        deptObj.getChildren().add(dept);

                        break;
                    }
                }
            }
        }
        return treeAll;
    }
}
